package com.kukudexin.client;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Option;
import com.kukudexin.test.MyTest;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;

import net.minidev.json.JSONArray;
import org.junit.Test;

public class AccessGameCenter {
    //访问userid
    @Test
    public void testUserId() {
        String json = getHistoryJson2();
        if (json != null) {
            //使用JsonPath解析数据
            ReadContext rc = JsonPath.parse(json);
            //获取userid
            String userid = rc.read("$.userid");
            System.out.println("获取的userid：" + userid);
        }
    }

    //访问userid
    @Test
    public void testUserId2() {
        String json = getHistoryJson2();
        if (json != null) {
            Configuration configuration = Configuration.builder().options(Option.DEFAULT_PATH_LEAF_TO_NULL).build();
            //使用JsonPath解析数据
            ReadContext rc = JsonPath.parse(json,configuration);
            //获取userid
            String userid = rc.read("$.userid");
            System.out.println("获取的userid：" + userid);
        }
    }
    @Test
    public void testCharge() {
        String json = getHistoryJson();
        if (json != null) {
            ReadContext rc = JsonPath.parse(json);
            //获取全部的充值记录
            //Object charge = rc.read("$.charge[*]");
            //获取第一条充值记录
            //Object charge = rc.read("$.charge[0,1]");
            Object charge = rc.read("$.charge[:2]");
            System.out.println(charge);
        }
    }

    /**
     * 按指定格式显示数据
     * 充值时间  金额  渠道 充值结果
     *
     * @return
     */
    @Test
    public void testChargeList() {
        String json = getHistoryJson();
        if (json != null) {
            String cdate = "";
            Integer coin = 0;
            String channel = "";
            String status = "";
            ReadContext rc = JsonPath.parse(json);
            List<Object> chargeList = rc.read("$.charge[*]");
            for (Object obj : chargeList) {
                Map<String, Object> map = (Map<String, Object>) obj;
                cdate = (String) map.get("cdate");
                coin = (Integer) map.get("coin");
                channel = (String) map.get("channel");
                status = (0 == (Integer) map.get("status")) ? "成功" : "失败";
                System.out.println(cdate + "\t" + coin + "\t" + channel + "\t" + status);
            }
        }
    }


    @Test
    public void testChargeCount() {
        String json = getHistoryJson2();
        if (json != null) {
            ReadContext rc = JsonPath.parse(json);
            Integer nums = rc.read("$.charge.length()");
            System.out.println("充值的记录总数:" + nums);

            //成功的充值记录数
            JSONArray array = rc.read("$.charge[?(@.status == 0)]");
            int size = array.size();
            System.out.println("充值成功的记录数：" + size);

            JSONArray array2 = rc.read("$.charge[?(@.status == 1)]");
            size = array2.size();
            System.out.println("充值失败的记录数：" + size);
        }

    }

    @Test
    public void testChargeCoin() {
        String json = getHistoryJson2();
        if (json != null) {
            ReadContext rc = JsonPath.parse(json);
//			JSONArray  array  = rc.read("$.charge[?(@.status == 0)]");
//
//			int len =array.size();
//			for(int i=0;i<len;i++){
//				Object obj = array.get(i);;
//				System.out.println(obj);
//			}

            List<Number> nums = rc.read("$.charge[?(@.status == 0 )].coin");
            double sum = 0;
            for (Number n : nums) {
                sum = sum + n.doubleValue();
            }
            System.out.println("充值成功的金额：" + sum);
        }
    }

    //统计消费：按服务器统计。每个服务器消费了多少钻石
    @Test
    public void testConsume() {
        String json = getHistoryJson2();
        double sum = 0;
        if (json != null) {
            ReadContext rc = JsonPath.parse(json);
            List<String> servers = rc.read("$..server");
            //去除重复，使用Set
            Set<String> set = new HashSet<String>(servers);
            //遍历服务器名称
            Iterator<String> iter = set.iterator();
            while (iter.hasNext()) {
                sum = 0;
                String ser = iter.next();
                System.out.println("服务器名称：" + ser);
                //组成jsonpath
                String path = "$.consume[?(@.server == '" + ser + "')].['coin','amount']";
                JSONArray array = rc.read(path);
                //遍历数组
                for (int i = 0, len = array.size(); i < len; i++) {
                    Map<Number, Number> data = (Map<Number, Number>) array.get(i);
                    Number c = data.get("coin");
                    Number a = data.get("amount");
                    double result = c.doubleValue() * a.doubleValue();
                    sum = sum + result;
                }
                System.out.println("消费总额：" + sum);
            }
        }
    }


    // 通过网络，访问gamecenter项目，一般可以使用 HttpClient, spring中RestTemplate完成远程访问。
    public String getHistoryJson() {
        //创建HttpClient远程访问gamecenter
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //指定访问的url地址
        String url = "http://localhost:8080/gamecenter/game";

        //构建Http GET请求
        HttpGet httpGet = new HttpGet(url);

        //创建应答对象Response;
        CloseableHttpResponse response = null;

        String text = null;
        //执行远程访问，获取接口数据
        try {
            response = httpClient.execute(httpGet);
            //判断请求是否正确返回
            if (response.getStatusLine().getStatusCode() == 200) {
                //请求成功，获取返回结果
                text = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (ClientProtocolException e) {
            text = null;
            e.printStackTrace();
        } catch (IOException e) {
            text = null;
            e.printStackTrace();
        }
        return text;
    }
    public String getHistoryJson2(){
        InputStream in = MyTest.class.getClassLoader().getResourceAsStream("history.json");
        ReadContext rc = JsonPath.parse(in);
        return rc.jsonString();
    }
}
